(
    function (factory) {
        if (typeof define === "function" && define.amd) {

            // AMD. Register as an anonymous module.
            define(["jquery", "./version"], factory);
        } else {

            // Browser globals
            factory(jQuery);
        }
    }
        (function ($) {
            var instance = {}
            var Editor = function (op) {
                var scriptMaps = {};
                _this = this;
                _this.options = op;
                var dragOp = {
                    connectToSortable: ".workspace",
                    helper: "clone",
                    handle: ".drag",
                    drag: function (t, e) {
                        e.helper.width(600)
                    },
                    stop: onStop
                }

                function onStop(t, e) {
                    e.helper.removeAttr("style");
                    var target = t.target;
                    $(".workspace .column").sortable({
                        opacity: .35,
                        connectWith: ".column"
                    })

                    var wid = $(t.target).attr("widget-id");
                    var scripts = scriptMaps[wid];

                    if (scripts) {
                        var view = $(e.helper[0], '.view')[0];
                        var loaded = 0;
                        function loadScript(index) {
                            if (index >= scripts.length)
                                return;
                            var newScript = document.createElement('script');
                            newScript.type = 'text/javascript';
                            newScript.src = scripts[index].src;
                            newScript.onload = function (e) {
                                loaded++;
                                loadScript(loaded);
                            }
                            view.appendChild(newScript);
                        }
                        loadScript(0);
                    }
                }

                function clearDemo() {
                    $(".workspace").empty()
                }

                function removeMenuClasses() {
                    $("#menu-layoutit li button").removeClass("active")
                }

                var _options = op;
                function init() {
                    var widgets = _options.widgets;
                    var wdlist = $("#widget-list")
                    //set widgets list
                    wdlist.empty()
                    widgets.forEach(function (ele) {
                        var tpl = ele.template;
                        if (tpl && tpl != "") {
                            $.get(tpl, function (data) {
                                var styles = "";
                                var body = data;
                                var scripts = "";
                                if (ele.styles) {
                                    ele.styles.forEach(function (se) {
                                        styles += '<link rel="stylesheet" href="' + se.href + '">'
                                    })
                                }
                                scriptMaps[ele.id] = [];
                                if (ele.scripts) {
                                    ele.scripts.forEach(function (se) {
                                        //scripts += '<script type="text/javascript" src='+se.url+'></script>'

                                        scriptMaps[ele.id].push(se)
                                    })
                                }

                                var html =
                                    '<div class="lyrow ui-draggable" widget-id="' + ele.id + '">' +
                                    '<a href="http://www.layoutit.com/build#close" class="remove label label-danger">' +
                                    '<i class="glyphicon-remove glyphicon"></i> remove' +
                                    '</a>' +
                                    '<span class="drag label label-default ui-draggable-handle">' +
                                    '<i class="glyphicon glyphicon-move"></i> drag' +
                                    '</span>' +
                                    '<div class="preview">' +
                                    '    <p>' + ele.name + '</p>' +
                                    '</div>' +
                                    '<div class="view">' +
                                    styles + body +
                                    '</div>' +
                                    '</div>';
                                $(html).appendTo(wdlist);
                                $(".editor-left-sidebar .lyrow").draggable(dragOp);
                            })
                        }
                    });
                    //set controls
                    $("body").css("min-height", $(window).height() - 90);
                    $(".workspace").css("min-height", $(window).height() - 160);
                    $(".workspace, .workspace .column").sortable({
                        connectWith: ".column",
                        opacity: .35,
                        handle: ".drag",
                        stop: function (event, ui) {

                        }
                    });
                    $(".editor-left-sidebar .lyrow").draggable(dragOp);
                    $(".workspace").on("click", ".remove", function (t) {
                        t.preventDefault();
                        $(this).parent().remove();
                        !$(".workspace .lyrow").length > 0 && $(".workspace").empty()
                    });
                    $("#edit").click(function () {
                        return $("body").removeClass("devpreview sourcepreview"),
                            $("body").addClass("edit"),
                            removeMenuClasses(),
                            $(this).addClass("active"), !1
                    });
                    $("#clear").click(function (t) {
                        t.preventDefault(),
                            clearDemo()
                    });
                    $("#devpreview").click(function () {
                        return $("body").removeClass("edit sourcepreview"),
                            $("body").addClass("devpreview"),
                            removeMenuClasses(),
                            $(this).addClass("active"), !1
                    });
                    $("#sourcepreview").click(function () {
                        return $("body").removeClass("edit"),
                            $("body").addClass("devpreview sourcepreview"),
                            removeMenuClasses(),
                            $(this).addClass("active"), refresh(), !1
                    })
                }

                function start() {
                    init();
                }
                this.start = start;
            }
            var editorInit = function () {
                $.get("/api/widgets", function (data) {
                    var editor = new Editor(data)
                    instance = editor;
                    instance.start();
                });
            };
            $(editorInit);
        })
);


